using System;
using Wandor;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Threading;

namespace Wandor.Server
{
	class Entry
	{
		
		public static void Main (string[] args)
		{
			
			var listener = new TcpListener(IPAddress.Any, 3366);
			
			Console.WriteLine("[SERVER]: Starting listener on port 3366...");
			
			listener.Start();
			
			Console.WriteLine("[SERVER]: Listener running, awaiting connections...");
			
			while(true)
			{
				var con = listener.AcceptTcpClient();
				
				if(!con.Connected)
					continue;
				
				Console.WriteLine("[LISTENER]: Connection from: " + con.Client.RemoteEndPoint);
				var reader = new BinaryReader(con.GetStream());
				
				if(con.GetStream().DataAvailable)
				{
					var opcode = reader.ReadInt32();
					
					if(opcode == (int)Opcode.CMSG_NEW_LOOKUP)
					{
						Thread.Sleep(1000);
						var guid = reader.ReadString();
						var sfrom = reader.ReadString();
						var sto = reader.ReadString();
						var choices = reader.ReadUInt32();
						
						Console.WriteLine("[LISTENER]: Got packet CMSG_NEW_LOOKUP:\n\tGuid: {0}\n\tFrom: {1}\n\tTo: {2}\n\tChoices: {3}", guid, sfrom, sto, choices);
						reader.Close();
						con.Close();
					}
				}
				
				reader.Close();
				Thread.Sleep(100);
			}
			
			
		}
	}
}

